package com.algorithm.tencent;

public class StringToInteger {
    public static void main(String[] args) {
        String s = "9223372036854775808";
        System.out.println(myAtoi(s));
    }

    public static int myAtoi(String str) {
        str = str.trim();
        if (str.length()== 0){
            return 0;
        }
        int length = str.length();
        int i = 0;
        long res = 0;
        int sign = 1;
        if (str.charAt(i) == 43) {
            i++;
        }else if(str.charAt(i) == 45) {
            sign = -1;
            i++;
        }
        if (i == length){
            return 0;
        }
        while (length > i && str.charAt(i) >= 48 && str.charAt(i) <= 57) {
            res = res * 10 + (str.charAt(i) -48);
            i++;
            if (res > Integer.MAX_VALUE){
                return sign ==1?Integer.MAX_VALUE:Integer.MIN_VALUE;
            }
        }
        return (int) (res * sign);
    }
}
